import html2canvas from 'html2canvas';
import jsPDF from 'jspdf'
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';


export const htmlToPDF = async (htmlId : string, title : string = "报表", bgColor = "#fff") => {
	let pdfDom : HTMLElement | null = document.getElementById(htmlId) as HTMLElement
	pdfDom.style.padding = '10px !important'
	const A4Width = 595.28;
	const A4Height = 841.89;
	let canvas = await html2canvas(pdfDom, {
		scale: 2,
		useCORS: true,
		backgroundColor: bgColor,
	});
	let pageHeight = (canvas.width / A4Width) * A4Height;
	let leftHeight = canvas.height;
	let position = 0;
	let imgWidth = A4Width;
	let imgHeight = (A4Width / canvas.width) * canvas.height;
	/*
	 根据自身业务需求  是否在此处键入下方水印代码
	*/
	let pageData = canvas.toDataURL("image/jpeg", 1.0);
	let PDF = new jsPDF("p", 'pt', 'a4');
	if (leftHeight < pageHeight) {
		PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
	} else {
		while (leftHeight > 0) {
			PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
			leftHeight -= pageHeight;
			position -= A4Height;
			if (leftHeight > 0) PDF.addPage();
		}
	}
	PDF.save(title + ".pdf");
}

/**
 * 导出Excel表格
 * @param name 生成excel的文件名，如：interestTable.xlsx
 * @param tableName 表格的id，如：#tableId
 * */
export const exportExcel = (tableName, name) => {
	let sel = XLSX.utils.table_to_book(document.querySelector(tableName))
	let selIn = XLSX.write(sel, { bookType: 'xlsx', bookSST: true, type: 'array' })

	try {
		FileSaver.saveAs(new Blob([selIn], { type: 'application/octet-stream' }), name)
	} catch (e) {
		if (typeof console !== 'undefined') console.log(e, selIn)
	}

	return selIn
}

export function exportToImage(elementId, fileName) {
	const element = document.getElementById(elementId);
	html2canvas(element).then(canvas => {
		canvas.toBlob(blob => {
			FileSaver.saveAs(blob, `${fileName}.png`); // save as PNG file with specified name and extension .png
		});
	});
}